<style lang="less" scoped>
.search {
  margin-left: 40px;
}
.el-pagination {
  padding-bottom: 50px;
}
.addsnForm {
  margin-bottom: 0;
}
.addsnForm /deep/.el-form-item__content .el-input {
  width: 320px !important;
}
.addsnForm /deep/.el-form-item__content .el-input + .el-button {
  margin-left: 20px;
}
/deep/.el-dialog__footer {
  padding-top: 0;
}
</style>
<template>
  <div class="device_control">
    <el-form :model="deviceControl" :inline="true">
      <el-form-item label="用户名"><el-input v-model="deviceControl.username" placeholder="用户名" disabled></el-input></el-form-item>
      <el-form-item label="时间节点">
        <el-date-picker
          v-model="sn_date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="创建日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
          @change="changeDate"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="设备SN"><el-input v-model.trim="deviceControl.sn" placeholder="设备SN" style="width: 120%"></el-input></el-form-item>
      <el-button type="primary" @click="onSearch" class="search"><i class="el-icon-search"></i><span>查询</span></el-button>
      <el-button type="primary" @click="onDelete"><i class="el-icon-delete"></i><span>批量删除</span></el-button>
      <el-button type="primary" @click="snFormVisible = true"> <i class="el-icon-circle-plus-outline"></i><span>新增</span></el-button>
      <el-button type="primary" @click="onExport"><i class="el-icon-download"></i><span>导出</span></el-button>
    </el-form>
    <el-table :data="tableData" border @selection-change="handleSelectionChange" v-loading="table_loading" ref="multipleTable">
      <template slot="empty"><i class="iconfont icon-kong"></i>暂无数据</template>
      <el-table-column width="50" type="selection"></el-table-column>
      <el-table-column label="序列" width="60"><template slot-scope="scope">{{ (scope.$index + pagingParams.size * (pagingParams.current - 1)) + 1 }}</template></el-table-column>
      <el-table-column label="ID" width="60" prop="id"></el-table-column>
      <el-table-column label="用户名" width="200" prop="username" ></el-table-column>
      <el-table-column sortable label="创建时间" width="200" prop="createTime" ></el-table-column>
      <!-- <el-table-column
        sortable
        label="修改时间"
        width="200"
        prop="lastUpdateTime"
      ></el-table-column> -->
      <el-table-column label="设备SN" width="300" prop="sn"></el-table-column>
       <el-table-column label="状态" width="100" prop="status"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button> -->
          <el-popconfirm
            confirmButtonText="确认"
            cancelButtonText="取消"
            title="确定要删除该设备SN吗？"
            @onConfirm="handleDelete(scope.$index, scope.row)"
            style="margin-left: 5px"
          >
            <el-button size="mini" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
          <!-- <el-switch
            style="margin-left:10px;"
            active-text="启用"
            inactive-text="禁用"
            @change="changeSnStatus(scope.$index, scope.row)"
          ></el-switch>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagingParams['current']"
      :page-sizes="[20, 40, 60, 80, 100, 200, 300, 400]"
      :page-size="pagingParams['size']"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagingParams['total']"
     ></el-pagination>

    <el-dialog title="新增设备SN" :visible.sync="snFormVisible" width="517px">
      <el-form :model="addSnForm" :rules="addSnForm.SnRule" label-width="auto" ref="addSnRule" class="addsnForm">
        <el-form-item label="用户名"> <el-input v-model="addSnForm.username" disabled style="width: 320px"></el-input></el-form-item>
        <!-- <el-form-item prop="sn" label="SN0">
          <el-input v-model="addSnForm.sn"></el-input>
        </el-form-item> -->
        <el-form-item
          v-for="(snNpt, index) in addSnForm.snNpts"
          :label="'SN' + index"
          :key="snNpt.key"
          :prop="'snNpts.' + index + '.sn'"
          :rules="{
            required: true,
            message: '设备SN不能为空',
            trigger: 'blur',
          }">
          <el-input v-model.trim="snNpt.sn"></el-input>
          <el-button @click.prevent="removeSnNpt(snNpt)">删除</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addSnNpt">新增SN</el-button>
        <el-button @click="resetSnForm('addSnRule')">重置</el-button>
        <el-button @click="snFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSnHandler('addSnRule')">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { deviceList, addDevice, deviceStatus } from "@/api/deviceControl"
import moment from "moment"
import cookies from "js-cookie"
import { pickerOptions } from '@/utils'
import { getUser } from '@/utils/auth'
export default {
  name: "deviceControl",
  data() {
    return {
      snFormVisible: false,
      loading: true,
      table_loading: false,
      deviceControl: {
        username: "",
        sn: "",
      },
      // 日期
      pickerOptions: pickerOptions(),
      sn_date: "",

      tableData: [],
      multipleSelection: [], //多选删除

      // 分页
      pagingParams: {
        // username: "",
        sn: "",
        createDateFrom: "",
        createDateTo: "",
        current: 1, //默认当前页数为1
        size: 20,
        total: 0,
        status: "ENABLED",
      },
      // 新增设备SN
      addSnForm: {
        username: "",
        sn: "",
        SnRule: {
          sn: [{ required: true, message: "设备SN不能为空", trigger: "blur" }],
        },
        snNpts: [{ sn: "" }],
      },
      username() {
        return getUser().username
      },
    }
  },
  methods: {
    changeDate() {
      let date = this.sn_date
      let _d = this.pagingParams
      date && date.length
        ? ((_d.createDateFrom = moment(date[0]).format("YYYY-MM-DD")),
          (_d.createDateTo = moment(date[1]).format("YYYY-MM-DD")))
        :  _d.createDateFrom = _d.createDateTo = null
    },
    // 查询
    onSearch() {
      this.pagingParams.current = 1
      // this.pagingParams.createDateFrom = moment(this.sn_date).format("YYYY-MM-DD HH:mm:ss")
      // this.pagingParams.createDateFrom = ' 2020-09-25T11:19:47.216Z'
      this.pagingParams.sn = this.deviceControl.sn
      this.getDeviceList()
    },
    // 拉去设备列表
    getDeviceList() {
      this.table_loading = true
      deviceList(this.pagingParams).then((res) => {
        this.pagingParams.size = res.data.size
        this.pagingParams.current = res.data.current
        this.pagingParams.total = res.data.total
        this.tableData = res.data.records.reverse()
        this.tableData.map((x) => {
          x.username = getUser().username
        })
        this.table_loading = false
      })
      this.tableData = this.tableData.reverse()
    },

// 删除sn
    handleDelete(x, y) {
      // let status = function () {
      //   // if(y.status) { return 'ENABLED' } else { return 'DISABLED' }
      // }
      deviceStatus({ datas: y.sn, status: "DISABLED" }).then((res) => {
        if (res.code == 0 && res.data) {
          this.$message({
            message: res.msg,
            type: "success",
            durantion: 2 * 1000,
          })
          this.getDeviceList()
        } else {
          this.$message({
            message: res.msg,
            type: "warning"
          })
        }
      })
    },

  // 批量删除
    onDelete() {
      if (this.multipleSelection.length !== 0) {
        this.$confirm("此操作将永久删除已选设备SN, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
            for (let i = 0; i < this.multipleSelection.length; i++) {
              deviceStatus({
                datas: this.multipleSelection[i].sn,
                status: "DISABLED",
              }).then((res) => {
                if (res.code == 0 && res.data) {
                  if(i + 1 >= this.multipleSelection.length) {
                  this.onSearch()
                  this.$message({
                   type: "success",
                   message: "删除成功!",
                 })
                  } 
                }
              })
            }
          
          }).catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            })
            this.$refs.multipleTable.clearSelection()
          })
      } else {
        this.$message({
          message: "请勾选要删除的设备SN",
          type: "warning"
        })
      }
    },

    // -------------------------------新建设备-------------------------------------
    // 新增设备sn输入框
    addSnNpt() {
      if (this.addSnForm.snNpts.length < 11) {
        this.addSnForm.snNpts.push({
          value: "",
          key: Date.now(),
        })
      } else {
        this.$message({
          message: "每次提交最多新增10个",
          type: "warning"
        })
      }
    },
    // 删除设备sn输入框
    removeSnNpt(item) {
      var index = this.addSnForm.snNpts.indexOf(item)
      if (index !== -1) {
        this.addSnForm.snNpts.splice(index, 1)
      }
    },
    //重置新增设备npt
    resetSnForm(addSnRule) {
      this.$refs[addSnRule].resetFields()
    },
    // 提交设备sn
    addSnHandler(addSnRule) {
      let _this = this
      this.$refs[addSnRule].validate((validSn) => {
        if (validSn) {
          // addHandler(this.addSnForm.sn)
          this.addSnForm.snNpts.forEach((val) => {
            addHandler(val.sn)
          })
        
        }
      })
      function addHandler(x) {
        addDevice({ datas: x }).then((res) => {
          // if (res.code == 10200) {
          //   this.$message({
          //     message: "该设备SN已存在",
          //     type: "warning",
          //     durantion: 3 * 1000,
          //   })
          // } else
          // 忽略库里是否已存在sn,都为成功新增
          if (res.code == 0 || res.code == 10200) {
            _this.getDeviceList()
            _this.$refs[addSnRule].resetFields()
            _this.snFormVisible = false
              _this.$message.success(`${x} 新增成功`)
          }  
        })
      }
    },
    onExport() {},
    handleEdit(index, row) {
      console.log(index, row)
    },
    // 分页
    handleSizeChange(val) {
      this.pagingParams.size = val
      this.getDeviceList()
    },
    handleCurrentChange(val) {
      this.pagingParams.current = val
      this.getDeviceList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
  },
  created() {
    this.getDeviceList()
  },
  mounted() {
    this.tableData.map((x) => {
      x.username = this.username()
    })
    this.addSnForm.username = this.deviceControl.username = this.username()
  },
}
</script>
